<script setup lang="ts">
import { ref } from 'vue'
import { Edit, Delete,Plus } from '@element-plus/icons-vue'
import { reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
//引入富文本编辑器
import { QuillEditor } from "@vueup/vue-quill";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  artGetChannelsService,
  artListChannelsService,
  addArticleService,
  updateArticleService,
  deleteArticleService,
  exportArticleService
} from '@/api/article.js'
import {useTokenStore} from '@/stores/token.js'

const title = ref()
const dialogVisible = ref(false)
const drawer = ref(false)

const categoryModel = ref({
  id: '',
  categoryName: '',
  categoryAlias: '',
  createTime: '',
  updateTime: ''
})

const categoryId = ref('')
const state = ref('')
//获取token
const token = useTokenStore().token;

const currentPage4 = ref(1)
const pageSize4 = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref(40)

const handleSizeChange = (val: number) => {
  pageSize4.value = val
  articleList()
}
const handleCurrentChange = (val: number) => {
  currentPage4.value = val
  articleList()
}
const tableData = ref([
  {
    id:'',
    title: '标题',
    categoryId: '时事',
    createTime: '2016-05-03',
    state: '已发布',
    coverImg: '',
    content: ''
  },
])
const articleModel = ref({
  id:'',
  title:'',
  categoryId:'',
  coverImg:'',
  content:'',
  state:''
})

//展示文章分类
async function articleCategoryList(){
  let result = await artGetChannelsService();
  console.log(result.data)
  categoryModel.value = result.data
  console.log(categoryId)
}

articleCategoryList();

//获取文章列表数据
async function articleList(){
  let params = {
    pageNum: currentPage4.value,
    pageSize:pageSize4.value,
    categoryId: categoryId.value ? categoryId.value : null,
    state: state.value ? state.value : null
  }
  let result = await artListChannelsService(params)
  console.log('文章数据',result.data)

  //获取数据，并进行赋值
  total.value = result.data.total;
  tableData.value = result.data.item;
}

articleList()

//重置按钮
function reset(){
  categoryId.value = ''
  state.value = ''
}

//文件上传成功回调函数
function uploadSuccess(res){
  articleModel.value.coverImg = res.data;
}

//添加文章
async function openPublic(state){
  //根据状态改变对象数据
  articleModel.value.state = state
  //同步等待异步调用函数
  let res = await addArticleService(articleModel.value)
  //提示消息
  ElMessage.success("添加成功");
  //关闭抽屉
  drawer.value = false;
  //刷新数据
  articleList()
}

//编辑文章
function MyEdit(row){
  console.log(row.content)
  title.value = '编辑文章';
  drawer.value = true;
  articleModel.value.id = row.id
  articleModel.value.title = row.title
  articleModel.value.categoryId = row.categoryId
  articleModel.value.coverImg = row.coverImg
  articleModel.value.content = row.content
  articleModel.value.state = row.state
}

//更新文章
async function updateArticle(){
  console.log(articleModel.value)
  let res = await updateArticleService(articleModel.value);
  //提示消息
  ElMessage.success("修改成功");
  //关闭抽屉
  drawer.value = false;
  //刷新数据
  articleList()
}

//清空数据
function clearData(){
  articleModel.value.title='';
  articleModel.value.categoryId='';
  articleModel.value.coverImg='';
  articleModel.value.content='';
  articleModel.value.state=''
}

//删除文章
const deleteData = (row) => {
  ElMessageBox.confirm(
      '你确定要删除吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        let result = await deleteArticleService(row.id);
        ElMessage({
          type: 'success',
          message: ' 删除成功',
        })
        articleList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

//导出文章数据
 function exportExcel(){
  let result =  exportArticleService();
  console.log(result)
}


</script>

<template>
  <el-card style="width: 1200px">
    <div class="card-header">
      <span>文章管理</span>
      <el-button type="success" @click="exportExcel">导出文章数据</el-button>
      <el-button type="primary" @click="title='添加文章';drawer=true;clearData()">添加文章</el-button>
    </div>

    <div>
      <br>
      <hr>
      <br>
    </div>

    <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select style="width: 200px"
                v-model="categoryId"
                placeholder="请选择"
                clearable
            >
              <el-option
                  v-for="c in categoryModel"
                  :key="c.id"
                  :label="c.categoryName"
                  :value="c.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态">
            <el-select style="width: 200px"
                v-model="state"
                placeholder="请选择"
                clearable
            >
              <el-option label="已发布" value="已发布" />
              <el-option label="草稿" value="草稿" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="articleList">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="default" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
    <br>

    <el-table :data="tableData" style="width: 1260px">
      <el-table-column prop="title" label="文章标题" />
      <el-table-column prop="categoryId" label="分类" />
      <el-table-column prop="createTime" label="发表时间" />
      <el-table-column prop="state" label="状态" />
      <el-table-column label="操作" width="180px">
        <template #default="{row}">
          <el-button type="primary" :icon="Edit" circle @click="MyEdit(row)"/>
          <el-button type="danger" plain :icon="Delete" circle @click="deleteData(row)" />
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="drawer" :title="title" size="50%">
      <!-- 添加文章表单 -->
      <el-form :model="articleModel" label-width="100px">
        <el-form-item label="文章标题">
          <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
        </el-form-item>

        <el-form-item label="文章分类">
          <el-select placeholder="请选择" v-model="articleModel.categoryId">
            <el-option
                v-for="c in categoryModel"
                :key="c.id"
                :label="c.categoryName"
                :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章状态" v-if="title==='编辑文章'">
          <el-select placeholder="请选择" v-model="articleModel.state" >
            <el-option label="已发布" value="已发布" />
            <el-option label="草稿" value="草稿" />
          </el-select>
        </el-form-item>

        <el-form-item label="文章封面">
          <div class="cover-box">

            <!--
              auto-upload:设置是否自动上传,设置为true
              action:设置服务器接口路径(有跨域问题，所以也要加上/api)
              name:设置上传的文件字段名(对应于后端的名称file)
              headers:设置上传的请求头
              on-success:设置上传成功的回调函数
             -->

            <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization':token}"
              :on-success="uploadSuccess"
              >
              <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>

        </el-form-item>

        <el-form-item label="文章内容">
          <div class="editor">
            <!--富文本编辑器-->
            <quill-editor contentType="html" theme="snow" v-model:content="articleModel.content">
            </quill-editor>
          </div>
        </el-form-item>

        <el-form-item class="editor">
          <div v-if="title==='添加文章'">
            <el-button type="primary" @click="openPublic('已发布')">发布</el-button>
            <el-button type="info" @click="openPublic('草稿')">草稿</el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="updateArticle">确定</el-button>
            <el-button type="info" @click="drawer=false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>

    <br>

    <el-pagination
        class="em-p"
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[1, 2, 3, 4]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="jumper, total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>
  <br>


</template>

<style lang="scss" scoped>
.em-p{
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.card-header{
  display: flex;
  justify-content: space-between;
}

//抽屉样式
.cover-box {
  width: 120px; /* 设置盒子宽度 */
  height: 120px; /* 设置盒子高度 */
  position: relative;
  overflow: hidden;
  border: 2px solid #ccc; /* 设置实线边框 */
}

.cover-box .avatar {
  width: 100%; /* 图片宽度填满盒子 */
  height: 100%; /* 图片高度填满盒子 */
  object-fit: cover; /* 图片填充方式 */
}

.cover-box .avatar-uploader-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 将加号按钮居中定位 */
  font-size: 36px; /* 设置加号按钮大小 */
  color: #999; /* 设置颜色 */
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0; /* 设置占位背景颜色 */
  display: flex;
  justify-content: center;
  align-items: center;
}

//富文本编辑器样式
.editor{
  width: 100%;
  height: 200px;
}


</style>

